<?php

namespace app\api\controller\Product;

use think\Controller;
use think\Request;

class Order extends Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('Product.Order');

        $this->OrderProductModel = model('Product.OrderProduct');
        
        $this->CartModel = model('Product.Cart');

        $this->UserModel = model('User.User');

        $this->RecordModel = model('User.Record');

        $this->ProductModel = model('Product.Product');
    }
	
	// 软删除订单
	public function del()
	{
		$orderid = $this->request->param('orderid');
		
		$userid = $this->request->param('userid');
		
		$orders = $this->OrderModel->find($orderid);
		
		if(!$orders)
		{
		    $this->error('该订单不存在');
		}
		
		// 在判断是否是这个用户的订单，防止被乱改id删除
		if($orders['userid'] != $userid)
		{
			$this->error('非法删除订单');
		}
		
		$result = $this->OrderModel->destroy($orderid);
		
		if($result === FALSE)
		{
			$this->error('删除失败');
			
		}else{
			
			$this->success('删除成功');
		}
		
	}
	
	public function index()
	{
		$userid = $this->request->param('userid');

		$status = $this->request->param('status');

		$where = [];

		if(!empty($userid))
		{
			$where['userid'] = $userid;
		}

		if($status != 0)
		{
			$where['status'] = $status;
		}

		$orderList = $this->OrderModel->where($where)->order('id','desc')->select();

		foreach($orderList as $item)
		{
			$OrderProduct = $this->OrderProductModel->with('product')->where('orderid',$item['id'])->select();

			$item['OrderProduct'] = $OrderProduct;
		}

		$this->success('查询成功',null,$orderList);
	}
	
	// 立即评价
	public function evalua()
	{
		$params = $this->request->param();
		
		$product = $this->OrderProductModel->find($params['id']);
		
		if(!$product)
		{
		    $this->error('订单不存在');
		}
		
		$user = $this->UserModel->find($product['userid']);
		
		if(!$product)
		{
		    $this->error('该用户不存在');
		}
		
		$orders = $this->OrderModel->find($params['orderid']);
		
		if(!$orders)
		{
		    $this->error('该订单不存在');
		}
		
		// 封装数据
		// $OrderProductData = [
		//     'id' => $params['id'],
		//     'rate' => $params['rate'],
		//     'comment' => $params['comment']
		// ];
				
		if($_FILES)
		{
			$ProimgArr = [];
			// 多图上传
			foreach($_FILES as $key => $val)
			{
				$proimg = upload($key);
						
				if($proimg['code'] == 0)
				{
				    $this->error($proimg['msg']);
				}
				
				// 切割字符串
				$img = substr($proimg['data'],1,999);
				
				$ProimgArr[] = '"'.$img.'"';
			}
			// 分割字符串
			// 切割数组
			$ProimgStr = implode(",",$ProimgArr);
			
			$proimgStr = "[" . $ProimgStr ."]";
			
			// 将数组解析成json字符串
			// $data['proimg'] = json_encode($ProimgArr,JSON_FORCE_OBJECT);
		    
		}
		
		$ProductArr = [];
		
		// 判断多个商品一起评价
		$ProductList = $this->OrderProductModel->select();
		foreach($ProductList as $key => $item)
		{
			if($item['orderid'] == $product['orderid'])
			{
				$ProductArr[] = [
					'id' => $item['id'],
					'rate' => $params['rate'],
					'comment' => $params['comment'],
					'proimg' => (!empty($proimgStr)) ? $proimgStr : null 
				];
				
			}
			
		}
		
		// 开启事务
		$this->OrderModel->startTrans();
		$this->OrderProductModel->startTrans();
				
		// 
		$OrderProductStatus = $this->OrderProductModel->isUpdate(true)->saveAll($ProductArr);
		
		if($OrderProductStatus === FALSE)
		{
		    $this->error($this->OrderProductModel->getError());
		}
		
		// 订单商品数据
		$OrderData = [
			'id' => $orders['id'],
			'status' => 4
		];
		
		// 修改订单为立即评价
		$OrderStatus = $this->OrderModel->isUpdate(true)->save($OrderData);
		
		if($OrderStatus === FALSE)
		{
		    $this->OrderProductModel->rollback();
		    $this->error($this->OrderModel->getError());
		}
		
		// 
		if($OrderStatus === FALSE || $OrderProductStatus === FALSE)
		{
		    // 多图数组
		    $thumbsArr = json_decode($OrderProductData['proimg'],true);			
			// 删除本地图片
			foreach($thumbsArr as $key => $item)
			{
				// 删除本地
				@is_file('.' . '/' . $item) && unlink('.' . '/' . $item);
			}
		    $this->OrderModel->rollback();
		    $this->OrderProductModel->rollback();
		    $this->error('评价失败');
		}else{
		    $this->OrderModel->commit();
		    $this->OrderProductModel->commit();
		    $this->success('评价成功','/order/order/index');
		}
		
	}
	
	// 确定收货
	public function goods()
	{
		$orderid = $this->request->param('orderid');
		
		$userid = $this->request->param('userid');
		
		$User = $this->UserModel->find($userid);
		
		if(!$User)
		{
			$this->error('该订单用户不存在，请重新选择');
		}
		
		$Order = $this->OrderModel->find($orderid);
		
		if(!$Order)
		{
			$this->error('该订单不存在，请重新选择');
		}
		
		$data = [
			'id' => $orderid,
			'status' => 3
		];
		
		// 申请退货
		$result = $this->OrderModel->isUpdate(true)->save($data);
		
		if($result === FALSE)
		{
			$this->error('确定收货失败，请重新申请');
		}else{
			$this->success('确定收货成功');
		}
	}
	
	// 申请售后
	public function sales()
	{
		$orderid = $this->request->param('orderid');
		
		$userid = $this->request->param('userid');
		
		$comment = $this->request->param('comment');
		
		$User = $this->UserModel->find($userid);
		
		if(!$User)
		{
			$this->error('该订单用户不存在，请重新选择');
		}
		
		$Order = $this->OrderModel->find($orderid);
		
		if(!$Order)
		{
			$this->error('该订单不存在，请重新选择');
		}
		
		if($Order['userid'] != $userid)
		{
			$this->error('非法申请');
		}
		
		$data = [
			'id' => $orderid,
			'comment' => $comment,
			'status' => -2
		];
		
		if($_FILES)
		{
			$ProimgArr = [];
			// 多图上传
			foreach($_FILES as $key => $val)
			{
				$proimg = upload($key);
						
				if($proimg['code'] == 0)
				{
				    $this->error($proimg['msg']);
				}
				
				// 切割字符串
				$img = substr($proimg['data'],1,999);
				
				$ProimgArr[] = '"'.$img.'"';
			}
			// 分割字符串
			// 切割数组
			$ProimgStr = implode(",",$ProimgArr);
			
			$data['proimg'] = "[" . $ProimgStr ."]";
			
			// 将数组解析成json字符串
			// $data['proimg'] = json_encode($ProimgArr,JSON_FORCE_OBJECT);
		}
		
		// 申请退货
		$result = $this->OrderModel->isUpdate(true)->save($data);
		
		if($result === FALSE)
		{
			// 多图数组
			$thumbsArr = json_decode($data['proimg'],true);			
			// 删除本地图片
			foreach($thumbsArr as $key => $item)
			{
				// 删除本地
				@is_file('.' . '/' . $item) && unlink('.' . '/' . $item);
			}
			$this->error('申请售后失败，请重新申请');
		}else{
			$this->success('申请售后成功','/order/order/index');
		}
		
	}

    public function confirm()
    {
        $userid = $this->request->param('userid');

        $ids = $this->request->param('ids');

        $addrid = $this->request->param('addrid');

        $content = $this->request->param('content');
		
		$proid = $this->request->param('proid');
		
		$action = $this->request->param('action');
		
		if(!empty($action))
		{
			$CartList = $this->ProductModel->find($proid);
		}else{
			$CartList = model('Product.Cart')->with('product')->whereIn('cart.id',$ids)->where(['userid' => $userid])->select();
		}
		
        $user = model('User.User')->find($userid);

        $address = model('User.Address')->find($addrid);

        if(!$CartList)
        {
            $this->error('所选的商品不存在，请重新选择');
        }

        if(!$user)
        {
            $this->error('用户不存在，请注册');
        }

        if(!$address)
        {
            $this->error('所选的收货地址不存在，请重新选择');
        }

        /* 
            购物车 => 删除
            订单表 => 新增订单 1
            订单商品 => 把购物车的数据添加订单商品表 1
            更新用户积分
            新增消费记录
            更新商品库存
        */


        // 订单总价
        $total = 0;
		if(!empty($action))
		{
			// 购买商品数量是否小于商品库存
			if(1 >= $CartList['stock'])
			{
			    $this->error($CartList['name'] . '商品库存不足，请重新选择');
			}
			
			$price = $CartList['vip_price'] ? $CartList['vip_price'] : $CartList['price'];
						
			// 用户的积分是否足够
			$point = bcsub($user['point'],$price);
						
			if($point < 0)
			{
			    $this->error('您的积分不足，请及时充值');
			}
						
			// 计算出订单总价
			$total = $price;
			
		}else{
			
			foreach ($CartList as $key => $item) {
			    // 购买商品数量是否小于商品库存
			    if($item['nums'] > $item['product']['stock'])
			    {
			        $this->error($item['product']['name'] . '商品库存不足，请重新选择');
			    }
			
			    // 用户的积分是否足够
			    $point = bcsub($user['point'],$item['total']);
			
			    if($point < 0)
			    {
			        $this->error('您的积分不足，请及时充值');
			    }
			
			    // 计算出订单总价
			    $total += $item['total'];
				
			}
	
		}
		
		if(!empty($action))
		{
			// 开启事务
			$this->OrderModel->startTrans();
			$this->OrderProductModel->startTrans();
			$this->UserModel->startTrans();
			$this->RecordModel->startTrans();
			$this->ProductModel->startTrans();
		}else{
			// 开启事务
			$this->OrderModel->startTrans();
			$this->OrderProductModel->startTrans();
			$this->CartModel->startTrans();
			$this->UserModel->startTrans();
			$this->RecordModel->startTrans();
			$this->ProductModel->startTrans();
		}
        

        // 订单数据
        $OrderData = [
            'total' => $total,
            'userid' => $userid,
            'addrid' =>  $addrid,
            'code' => build_code('ASK'),
            'content' => $content,
            'status' => 1
        ];

        $OrderStatus = $this->OrderModel->validate('common/Product/Order')->save($OrderData);

        if($OrderStatus === FALSE)
        {
            $this->error($this->OrderModel->getError());
        }

        // 订单商品数据
        $OrderProductData = [];
		
		if(!empty($action))
		{
			$OrderProductData[] = [
			    'orderid' => $this->OrderModel->id,
			    'proid' => $CartList['id'],
			    'nums' => 1,
			    'price' => $CartList['price'],
			    'total' => $total,
			    'userid' => $userid
			];
			
		}else{
			
			foreach($CartList as $item)
			{
			    $OrderProductData[] = [
			        'orderid' => $this->OrderModel->id,
			        'proid' => $item['product']['id'],
			        'nums' => $item['nums'],
			        'price' => $item['price'],
			        'total' => $item['total'],
			        'userid' => $userid
			    ];
			}
		}
        
        $OrderProductStatus = $this->OrderProductModel->validate('common/Product/OrderProduct')->saveAll($OrderProductData);

        if($OrderProductStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->error($this->OrderProductModel->getError());
        }

        // 删除购物车
		if(empty($action))
		{
			$CartStatus = $this->CartModel->WhereIn('id',$ids)->delete();
			
			if($CartStatus === FALSE)
			{
			    $this->OrderModel->rollback();
			    $this->OrderProductModel->rollback();
			    $this->error($this->CartModel->getError());
			}
			
		}

        // 更新用户积分
        $UserData = [
            'id' => $userid,
            'point' => bcsub($user['point'],$total)
        ];

        $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

        if($UserStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->error($this->UserModel->getError());
        }

        // 新增消费记录
        $RecordData = [
            'point' => $total,
            'content' => "您的商品订单{$OrderData['code']}共消费了{$total}积分",
            'state' => 5,
            'userid' => $userid
        ];

        $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);

        if($RecordStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->error($this->RecordModel->getError());
        }

        // 更新商品的库存
        $ProductData = [];
		
		if(!empty($action))
		{
			$ProductData[] = [
			    'id' => $CartList['id'],
			    'stock' => bcsub($CartList['stock'],1)
			];
			
		}else{
			
			foreach($CartList as $item)
			{
			    $ProductData[] = [
			        'id' => $item['product']['id'],
			        'stock' => bcsub($item['product']['stock'],$item['nums'])
			    ];
			}
		}

        $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

        if($ProductStatus === FALSE)
        {
            $this->OrderModel->rollback();
            $this->OrderProductModel->rollback();
            $this->CartModel->rollback();
            $this->UserModel->rollback();
            $this->RecordModel->rollback();
            $this->error($this->ProductModel->getError());
        }

        if(!empty($action))
		{
			if($OrderStatus === FALSE || $OrderProductStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE)
			{
			    $this->OrderModel->rollback();
			    $this->OrderProductModel->rollback();
			    $this->UserModel->rollback();
			    $this->RecordModel->rollback();
			    $this->ProductModel->rollback();
			    $this->error('下单失败');
			}else{
			    $this->OrderModel->commit();
			    $this->OrderProductModel->commit();
			    $this->UserModel->commit();
			    $this->RecordModel->commit();
			    $this->ProductModel->commit();
			    $this->success('下单成功','/order/order/info',['orderid' => $this->OrderModel->id]);
			}
		}else{
			if($OrderStatus === FALSE || $OrderProductStatus === FALSE || $CartStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE || $ProductStatus === FALSE)
			{
			    $this->OrderModel->rollback();
			    $this->OrderProductModel->rollback();
			    $this->CartModel->rollback();
			    $this->UserModel->rollback();
			    $this->RecordModel->rollback();
			    $this->ProductModel->rollback();
			    $this->error('下单失败');
			}else{
			    $this->OrderModel->commit();
			    $this->OrderProductModel->commit();
			    $this->CartModel->commit();
			    $this->UserModel->commit();
			    $this->RecordModel->commit();
			    $this->ProductModel->commit();
			    $this->success('下单成功','/order/order/info',['orderid' => $this->OrderModel->id]);
			}
		}
        
    }

    public function info()
    {
        $userid = $this->request->param('userid');

        $orderid = $this->request->param('orderid');

        $user = $this->UserModel->find($userid);

        if(!$user)
        {
            $this->error('用户不存在，请重新注册');
        }

        /* 
            订单表
            订单商品表 （主表）
            商品表
            用户收货地址
        */

        // 订单
        $order = $this->OrderModel->find($orderid);

        // 订单商品
        $OrderProduct = $this->OrderProductModel->with('product')->where(['orderid' => $orderid])->select();

        // 收货地址
        $Address = model('User.Address')->with(['provinces','citys','districts'])->find($order['addrid']);
        
        if(!$order || !$OrderProduct || !$Address)
        {
            $this->error('订单不存在，请重新选择');
        }

        $data = [
            'order' => $order,
            'OrderProduct' => $OrderProduct,
            'address' => $Address
        ];

        $this->success('查询成功',null,$data);

    }
}
